<!--
 * @Author: WangLong
 * @Date: 2024-01-31 18:45:07
 * @LastEditTime: 2024-05-08 17:06:56
 * @LastEditors: kls
 * @Description: 
 * @FilePath: \front_erp\src\views\stock\inoutStorage\index.vue
-->
<template>
  <div class="request">
    <div class="search-button">
      <el-button class="btn search" @click="getList"
        ><el-icon class="icon" color="#fff"> <Search /> </el-icon
        >查询</el-button
      >
      <el-button class="btn add" @click="handleRefresh"
        ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
        >重置</el-button
      >
      <el-button class="btn save" @click="handleExport('1')"
        ><el-icon class="icon" color="#fff"> <Download /> </el-icon
        >导出列表</el-button
      >
      <el-popover :width="170" trigger="click" placement="bottom">
        <template #reference>
          <el-button class="btn search" style="width: 100px"
            ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
            >显示列</el-button
          >
        </template>
        <el-checkbox-group v-model="checkList" @change="handleCheckChange">
          <div>
            <el-checkbox label="typeName">类型</el-checkbox>
          </div>
          <div>
            <el-checkbox label="applyCode">出/入/退库编号</el-checkbox>
          </div>
          <div>
            <el-checkbox label="projectCodeName">关联项目</el-checkbox>
          </div>
          <div>
            <el-checkbox label="applicantDate">日期</el-checkbox>
          </div>
          <div>
            <el-checkbox label="applicantName">操作人</el-checkbox>
          </div>
          <div>
            <el-checkbox label="batchCode">入库批次</el-checkbox>
          </div>
          <div>
            <el-checkbox label="warehouseCode">仓库</el-checkbox>
          </div>
          <div>
            <el-checkbox label="qty">数量</el-checkbox>
          </div>
          <div>
            <el-checkbox label="expireDate">厂家质保期</el-checkbox>
          </div>
          <div>
            <el-checkbox label="validityPeriod">授权有效期</el-checkbox>
          </div>
          <div>
            <el-checkbox label="fileList">物料图片</el-checkbox>
          </div>
          <div>
            <el-checkbox label="materialCode">物料编号</el-checkbox>
          </div>
          <div>
            <el-checkbox label="materialName">物料名称</el-checkbox>
          </div>
          <div>
            <el-checkbox label="factoryCode">出厂型号</el-checkbox>
          </div>
          <div>
            <el-checkbox label="technologyParameter">技术参数</el-checkbox>
          </div>
          <div>
            <el-checkbox label="materialUnitName">单位</el-checkbox>
          </div>
          <div>
            <el-checkbox label="purchasePrice">采购单价(元)</el-checkbox>
          </div>
          <div>
            <el-checkbox label="categoryName">物料分类</el-checkbox>
          </div>
          <div>
            <el-checkbox label="stockTypeName">存货类型</el-checkbox>
          </div>
          <div>
            <el-checkbox label="supplierName">供应商</el-checkbox>
          </div>
          <div>
            <el-checkbox label="manufactureName">生产厂商</el-checkbox>
          </div>
        </el-checkbox-group>
      </el-popover>
    </div>
    <!-- 筛选条件 -->
    <div class="search">
      <div class="search-item">
        <el-select
          v-model="params.inOutType"
          placeholder="请选择出库类型"
          clearable
          class="search-input"
          style="width: 8vw"
        >
          <el-option
            v-for="dict in inOutTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </div>
      <div class="search-item">
        <el-input
          clearable
          style="width: 8vw"
          v-model="params.materialNumber"
          class="search-input"
          placeholder="请输入序列号"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          style="width: 7vw"
          v-model="params.applicantName"
          class="search-input"
          placeholder="请输入操作人"
        ></el-input>
      </div>
      <div class="search-item">
        <el-date-picker
          v-model="time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </div>
      <div class="search-item">
        <el-input
          clearable
          style="width: 7vw"
          v-model="params.materialCode"
          class="search-input"
          placeholder="请输入物料编号"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          style="width: 7vw"
          v-model="params.materialName"
          class="search-input"
          placeholder="请输入物料名称"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          style="width: 7vw"
          clearable
          v-model="params.factoryCode"
          class="search-input"
          placeholder="请输入出厂型号"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          style="width: 8vw"
          clearable
          v-model="params.supplierName"
          class="search-input"
          placeholder="请输入供应商名称"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          style="width: 8vw"
          v-model="params.manufactureName"
          class="search-input"
          placeholder="请输入生产厂商名称"
        ></el-input>
      </div>
    </div>
    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="inoutstorageList"
      border
      height="60vh"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column
        type="index"
        label="序号"
        :index="indexMethod"
        width="70"
        align="center"
      />

      <el-table-column
        label="主设备物资序列号"
        :show-overflow-tooltip="true"
        min-width="100"
      >
        <template #default="{ row, $index }">
          <div class="table-operate" v-if="row.importantDevice == 1">
            <el-button @click="handleQrcode(row, $index)">查看</el-button>
          </div>
          <div class="table-operate" v-else>
            <el-button style="background-color: #ccc" disabled>查看</el-button>
          </div>
        </template></el-table-column
      >
      <el-table-column
        label="类型"
        prop="typeName"
        v-if="checkList.includes('typeName')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="出/入/退库编号"
        prop="applyCode"
        v-if="checkList.includes('applyCode')"
        :show-overflow-tooltip="true"
        min-width="130"
      >
        <template #default="{ row }">
          <span
            @click="handlepurchaseRequestDetail(row)"
            style="color: #409eff; cursor: pointer"
            >{{ row.applyCode }}</span
          >
        </template></el-table-column
      >
      <el-table-column
        label="关联项目"
        prop="projectCodeName"
        v-if="checkList.includes('projectCodeName')"
        :show-overflow-tooltip="true"
        min-width="180"
      />
      <el-table-column
        label="日期"
        prop="applicantDate"
        v-if="checkList.includes('applicantDate')"
        :show-overflow-tooltip="true"
        min-width="160"
      />
      <el-table-column
        label="操作人"
        prop="applicantName"
        v-if="checkList.includes('applicantName')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="入库批次"
        prop="batchCode"
        v-if="checkList.includes('batchCode')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="仓库"
        prop="warehouseCode"
        v-if="checkList.includes('warehouseCode')"
        :show-overflow-tooltip="true"
        min-width="100"
      />
      <el-table-column
        label="数量"
        prop="qty"
        v-if="checkList.includes('qty')"
        :show-overflow-tooltip="true"
        min-width="100"
      />
      <el-table-column
        label="序列号"
        prop="materialNumber"
        v-if="checkList.includes('materialNumber')"
        :show-overflow-tooltip="true"
        min-width="160"
      />
      <el-table-column
        label="厂家质保期"
        prop="expireDate"
        v-if="checkList.includes('expireDate')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="授权有效期"
        prop="validityPeriod"
        v-if="checkList.includes('validityPeriod')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="物料图片"
        prop=""
        v-if="checkList.includes('fileList')"
        :show-overflow-tooltip="true"
        min-width="100"
      >
        <template #default="{ row }">
          <div v-if="row.fileList" class="image-content">
            <el-image
              v-for="(item, index) in row.fileList"
              :key="index"
              :preview-teleported="true"
              style="width: 50px; height: 50px; margin-right: 5px"
              :src="item.url"
              :preview-src-list="showImg(item.url)"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><icon-picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="物料编号"
        prop="materialCode"
        v-if="checkList.includes('materialCode')"
        :show-overflow-tooltip="true"
        min-width="120"
      >
        <template #default="{ row }">
          <span>{{ row.materialCode ? row.materialCode : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="物料名称"
        prop="materialName"
        v-if="checkList.includes('materialName')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="出厂型号"
        prop="factoryCode"
        v-if="checkList.includes('factoryCode')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="技术参数"
        prop="technologyParameter"
        v-if="checkList.includes('technologyParameter')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="单位"
        prop="materialUnitName"
        v-if="checkList.includes('materialUnitName')"
        :show-overflow-tooltip="true"
        min-width="80"
      />
      <el-table-column
        label="采购单价(元)"
        prop="purchasePrice"
        v-if="checkList.includes('purchasePrice')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="物料分类"
        prop="categoryName"
        v-if="checkList.includes('categoryName')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="存货类型"
        prop="stockTypeName"
        v-if="checkList.includes('stockTypeName')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="供应商"
        prop="supplierName"
        v-if="checkList.includes('supplierName')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        label="生产厂商"
        prop="manufactureName"
        v-if="checkList.includes('manufactureName')"
        :show-overflow-tooltip="true"
        min-width="120"
      />
    </el-table>

    <!-- 分页 -->
    <pagination
      class="pagination"
      :total="total"
      v-model:page="params.pageNum"
      v-model:limit="params.pageSize"
      @pagination="getList"
    />
    <!-- 二维码弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="主设备序列号"
      width="36%"
      :close-on-click-modal="false"
    >
      <QrCodeInfo :qrcodeData="qrcodeData" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getDictsApi } from '@/api/dict'
import QrCodeInfo from '@/components/qrCode/index'
import { getInOutListApi } from '@/api/stock/inoutstorage'
import useUserStore from '@/store/modules/user'
import { addTableHeaderApi, getTableHeaderApi } from '@/api/pub'

const { proxy } = getCurrentInstance()
const router = useRouter()

const userStore = useUserStore()
// 表格加载效果
const loading = ref(false)
// 出库类型列表
const inOutTypeList = ref([])
//列表数据
const inoutstorageList = ref([])
// 总数
const total = ref(0)
//筛选时间
let time = ref([])
//控制查看二维码弹窗
const dialogVisible = ref(false)
//主设备物资序列号数据
const qrcodeData = ref([])
// 搜索参数
const params = reactive({
  inOutType: null, // 出库类型
  materialNumber: '', // 序列号
  applicantName: '', //操作人
  beginDate: '', //开始日期
  endDate: '', //结束日期
  materialCode: '', //物料编号
  materialName: '', // 物料名称
  factoryCode: '', //供应商名称
  supplierName: '', //生产厂商名称
  pageNum: 1,
  pageSize: 50,
})

const checkList = ref([
  'typeName',
  'applyCode',
  'projectCodeName',
  'applicantDate',
  'applicantName',
  'batchCode',
  'warehouseCode',
  'qty',
  'expireDate',
  'validityPeriod',
  'fileList',
  'materialCode',
  'materialName',
  'factoryCode',
  'technologyParameter',
  'materialUnitName',
  'purchasePrice',
  'categoryName',
  'stockTypeName',
  'supplierName',
  'manufactureName',
])

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(',')
  const result = await addTableHeaderApi({
    moduleType: 32,
    titleField: str,
  })
}

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 32,
  })
  if (result.code == 200) {
    var arr = result.data.titleField.split(',')
    checkList.value = arr
  }
}

/**
 * @description: 重置
 */
const handleRefresh = () => {
  time.value = []
  Object.assign(params, {
    inOutType: null, // 出库类型
    materialNumber: '', // 序列号
    applicantName: '', //操作人
    beginDate: '', //开始日期
    endDate: '', //结束日期
    materialCode: '', //物料编号
    materialName: '', // 物料名称
    factoryCode: '', //供应商名称
    supplierName: '', //生产厂商名称
    manufactureName: '',
    pageNum: 1,
    pageSize: 50,
  })
  getList()
}

/**
 * @description: 获取出入库列表
 */
const getList = async () => {
  try {
    loading.value = true
    let { pageNum, pageSize } = params
    if (time.value != null && time.value.length > 0) {
      params.beginDate = time.value[0]
      params.endDate = time.value[1]
    } else {
      params.beginDate = ''
      params.endDate = ''
    }
    const res = await getInOutListApi({ pageNum, pageSize }, params)
    inoutstorageList.value = res.rows
    total.value = res.total
    loading.value = false
  } catch {
    loading.value = false
  }
}
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum
  const pageSize = params.pageSize
  const truelndex = (currentPage - 1) * pageSize + index + 1
  return truelndex
}

const handleExport = async (flag) => {
  let date = timeFormat()

  let fileName = date + '库存'
  let { pageNum, pageSize } = params
  params.fileName = fileName

  /* 导出列表 */
  proxy.download(`/system/inOut/export`, params, `${fileName}.xlsx`, null, 1)
}

function timeFormat() {
  let dateTime = new Date()
  // 获取年份
  let Y = dateTime.getFullYear()
  //获取当前年的月份 月份要 + 1 （0代表1月）date.getMonth() + 1
  let M =
    dateTime.getMonth() + 1 < 10
      ? '0' + (dateTime.getMonth() + 1)
      : dateTime.getMonth() + 1
  //获取当前日（1 - 31）
  let D =
    dateTime.getDate() < 10
      ? '0' + dateTime.getDate() + ' '
      : dateTime.getDate() + ' '
  //获取当前小时（0-23）
  let h =
    dateTime.getHours() < 10 ? '0' + dateTime.getHours() : dateTime.getHours()
  //获取当前分钟（0-59）
  let m =
    dateTime.getMinutes() < 10
      ? '0' + dateTime.getMinutes()
      : dateTime.getMinutes()
  //获取当前秒数（0-59）
  let s =
    dateTime.getSeconds() < 10
      ? '0' + dateTime.getSeconds()
      : dateTime.getSeconds()

  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100)
  // 用户昵称
  let userName = userStore.name
  return Y + M + D + userName + randomNum
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  //出库类型
  await getDictsApi('erp_inout_type').then((res) => {
    if (res.code === 200) {
      inOutTypeList.value = res.data
    }
  })
}
const showImg = (img) => {
  let imgArr = []
  imgArr.push(img)
  return imgArr
}
/**
 * @description: 查看主设备物资序列号
 */
const handleQrcode = async (row) => {
  qrcodeData.value = []
  dialogVisible.value = true
  qrcodeData.value.push({
    materialNumber: row.materialNumber,
  })
}
/* 跳转出/入/退库审核详情 */
const handlepurchaseRequestDetail = (row) => {
  if (row.type == 1) {
    //出库详情
    const { href } = router.resolve({
      path: `/stock/outorderAudit`,
      query: { applyId: row.applyId },
    })
    window.open(href, '_blank')
    // window.open(`/stock/outorderAudit?applyId=${row.applyId}`, "_blank");
  } else if (row.type == 2) {
    //入库详情
    const { href } = router.resolve({
      path: `/stock/inorderAudit`,
      query: { applyId: row.applyId },
    })
    window.open(href, '_blank')
    // window.open(`/stock/inorderAudit?applyId=${row.applyId}`, "_blank");
  } else {
    //退库详情
    const { href } = router.resolve({
      path: `/stock/returnReview`,
      query: { applyId: row.applyId },
    })
    window.open(href, '_blank')
    // window.open(`/stock/returnReview?applyId=${row.applyId}`, "_blank");
  }
}
onMounted(() => {
  getDicts()
  getList()
  getTableHeader()
})
</script>

<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .table-operate {
    cursor: pointer;
    .el-button {
      height: 28px;
    }
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}
</style>
